package com.example.Servlet;

import com.example.Service.UserService;
import com.example.pojo.User;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "樊诗涵!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        setCorsHeaders(resp);
        resp.setStatus(HttpServletResponse.SC_OK);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        setCorsHeaders(resp);

        // 修复：正确读取请求体
        BufferedReader br = req.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String requestBody = sb.toString();

        System.out.println("收到登录请求: " + requestBody);

        // 如果请求体为空，返回错误
        if (requestBody == null || requestBody.trim().isEmpty()) {
            sendErrorResponse(resp, "请求数据不能为空");
            return;
        }

        try {
            Gson gson = new Gson();
            User user = gson.fromJson(requestBody, User.class);

            // 验证必要的字段
            if (user == null || user.getUserId() == 0 ||
                    user.getUserPwd() == null || user.getUserPwd().trim().isEmpty() ||
                    user.getRole() == null || user.getRole().trim().isEmpty()) {
                sendErrorResponse(resp, "用户名、密码和角色不能为空");
                return;
            }

            UserService userService = new UserService();
            User u = userService.check_login(user);

            Map<String, Object> map = new HashMap<>();
            if (u != null) {
                map.put("code", 200);
                map.put("msg", "登录成功");
                map.put("data", u);
            } else {
                map.put("code", 500);
                map.put("msg", "账号或密码错误");
            }

            String json = gson.toJson(map);
            System.out.println("登录响应: " + json);
            sendJsonResponse(resp, json);

        } catch (Exception e) {
            e.printStackTrace();
            sendErrorResponse(resp, "服务器内部错误: " + e.getMessage());
        }
    }

    // 设置CORS头
    private void setCorsHeaders(HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5501");
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Max-Age", "3600");
    }

    // 发送JSON响应
    private void sendJsonResponse(HttpServletResponse resp, String json) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        out.print(json);
        out.flush();
    }

    // 发送错误响应
    private void sendErrorResponse(HttpServletResponse resp, String errorMsg) throws IOException {
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("code", 400);
        errorMap.put("msg", errorMsg);

        Gson gson = new Gson();
        String json = gson.toJson(errorMap);
        sendJsonResponse(resp, json);
    }

    public void destroy() {
    }
}